using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using RestSharp;
using System.Collections.ObjectModel;
using LibVLCSharp.Shared; // 确保包含 LibVLCSharp.Shared 命名空间
using System.Linq;
using System.Threading.Tasks;
using System;
using System.Collections.Specialized; // For INotifyCollectionChanged
using System.Diagnostics;
using VideoClient;
using CommunityToolkit.Mvvm.Messaging;
using CommunityToolkit.Mvvm.Messaging.Messages;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.DependencyInjection;
using System.Windows;
using System.Reflection; // 用于 Debug.WriteLine

namespace vlcplay.ViewModels;

public partial class MainViewModel : ObservableObject, IDisposable
{
    // Replace the following line:
    private readonly ILogger<MainViewModel> logger = App.ServiceProvider.GetRequiredService<ILogger<MainViewModel>>();

    // With this corrected line:
    private LibVLC? _libvlc; // LibVLC can be initialized later
    private readonly XhVideoClient _videoClient;
    [ObservableProperty]
    private ObservableCollection<VideoItemViewModel> videoItems = new ObservableCollection<VideoItemViewModel>();

    [ObservableProperty]
    private string appVersion = string.Empty; // Initialize to a non-null value
    
    [ObservableProperty]
    private double availableItemsControlWidth; // Add property to hold available width

    [ObservableProperty]
    private string statusMessage;

    [ObservableProperty]
    private string currentUser;

    [ObservableProperty]
    private bool isLoading;

    // MainViewModel.cs
    public void ScheduleBatchSnapshotRefresh(XhVideoClient client)
    {
        _ = Task.Run(async () =>
        {
            // await Task.Delay(TimeSpan.FromMinutes(1));
            await Task.Delay(TimeSpan.FromSeconds(10));
            foreach (var item in VideoItems)
            {
                // 异步后台刷新，不影响当前显示
                _ = client.DownloadAndUpdateSnapshotAsync(item.myDevCh);
                logger.LogInformation($"更新预览{item.Device}_{item.Channel}");
            }
        });
    }

    public async Task LoadVideoListAsync()
    {
        IsLoading = true;
        try
        {
            await Task.Run(() =>
            {
                // Login and get token

                var token = _videoClient.AccessToken;
                if (string.IsNullOrEmpty(token))
                {
                    logger.LogWarning("No token, please login first.");
                    return;
                }

                // Get play code
                string playCode = _videoClient.GetCode(token);

                // Get device channels
                var devChResponse = _videoClient.GetDeviceChannels(token);

                // Update UI on dispatcher
                System.Windows.Application.Current.Dispatcher.Invoke(() =>
                {
                    Core.Initialize();
                    _libvlc = new LibVLC(enableDebugLogs: true);
                    // _libvlc.Log += OnLibVlcLog;
                    // Dispose and clear old items
                    foreach (var item in VideoItems)
                    {
                        item.Dispose();
                        logger.LogDebug($"VideoItems {item} Dispose");

                    }
                    VideoItems.Clear();

                    if (devChResponse?.Data != null)
                    {
                        List<DevCh> devChes = devChResponse.Data;
                        string refreshDevChsMsg = $"设备列表已更新，共{devChes.Select(x => x.Device).Distinct().Count()}个设备，{devChes.Count}个通道";
                        logger.LogInformation(refreshDevChsMsg);
                        WeakReferenceMessenger.Default.Send(new ValueChangedMessage<string>(refreshDevChsMsg));

                        // 按照 Channel 的最后4位子字符串升序排序
                        // 如果 Channel 为 null/空，则视为空字符串进行排序
                        // 如果 Channel 长度小于4，则使用整个 Channel 字符串进行排序
                        var orderedDevChs = devChes
                            .OrderBy(dc => 
                                string.IsNullOrEmpty(dc.Channel) ? string.Empty : 
                                dc.Channel.Length >= 4 ? dc.Channel.Substring(dc.Channel.Length - 4) : dc.Channel
                            )
                            .ToList();

                        foreach (DevCh dc in orderedDevChs) // 使用排序后的列表
                        {
                            string url = $"rtmp://47.108.206.80:1935/rtp/{dc.Device}_{dc.Channel}?code={playCode}";
                            logger.LogDebug($"Loading video: {url} for {dc.Name} ({dc.Device}_{dc.Channel})");
                            VideoItemViewModel videoItemViewModel = new VideoItemViewModel(_libvlc, url, dc);
                            VideoItems.Add(videoItemViewModel);
                            _ = videoItemViewModel.UpdatePreviewImageAsync(_videoClient);
                        }
                    }
                    // MaximizedVideo property was removed, no reset needed here for it.
                    // If a maximized window is open, it's independent.
                });
            });
        }
        finally
        {
            IsLoading = false;
        }
    }

    private void OnLibVlcLog(object? sender, LogEventArgs e)
    {
        Console.WriteLine(e.FormattedLog);
        logger.LogInformation(e.FormattedLog);
    }

    public MainViewModel(XhVideoClient videoClient)
    {
        _videoClient = videoClient;
        currentUser = "未登录"; // Initialize backing field for CurrentUser
        statusMessage = string.Empty; // Initialize statusMessage
        AppVersion = Assembly.GetExecutingAssembly().GetName().Version?.ToString() ?? "未知";
        logger.LogInformation($"程序启动，版本号：{AppVersion}");
        WeakReferenceMessenger.Default.Register<ValueChangedMessage<string>>(this, (r, m) =>
        { // statusMessage is initialized here or can be initialized with string.Empty
            StatusMessage = m.Value;
        });
        ScheduleBatchSnapshotRefresh(_videoClient);
        VideoItems.CollectionChanged += OnVideoItemsChanged;
    }
    private void OnVideoItemsChanged(object? sender, NotifyCollectionChangedEventArgs e)
    {
        OnPropertyChanged(nameof(VideoGridColumns));
    }

    // When AvailableItemsControlWidth changes, recalculate columns
    partial void OnAvailableItemsControlWidthChanged(double value)
    {
        OnPropertyChanged(nameof(VideoGridColumns));
    }

    public bool Login(string username, string password)
    {
        // 调用注入的 XhVideoClient 的登录方法
        bool success = false;
        var result = _videoClient.Login(username, password, out success);
        // 你可以根据 result 判断是否登录成功
        return !string.IsNullOrEmpty(_videoClient.AccessToken);
    }

    // 停止所有视频播放的命令
    [RelayCommand]
    public void StopAllVideos()
    {
        foreach (var item in VideoItems)
        {
            item.StopVideoCommand.Execute(null); // 使用 ViewModel 内部的命令
        }
    }

    // 播放所有视频的命令
    [RelayCommand]
    private async Task PlayAllVideos()
    {
        foreach (var item in VideoItems)
        {
            await item.PlayVideoCommand.ExecuteAsync(null); // Play all items in the grid
        }
    }

    // 最大化视频的命令，仅在正在播放时可用
    public bool CanMaximizeVideo(VideoItemViewModel? video)
    {
        return video != null; // 任何视频都可以被选择在最大化视图中播放
    }

    [RelayCommand(CanExecute = nameof(CanMaximizeVideo))]
    public async Task MaximizeVideo(VideoItemViewModel? video) // 改为 async Task
    {
        if (video == null) return;
        logger.LogInformation($"[MaximizeVideo_Command] Opening new window for {video.Device}_{video.Channel}");

        // Stop this video if it's playing in the grid (though grid doesn't play now)
        // video.StopVideoCommand.Execute(null);

        var maximizedWindowLogger = App.ServiceProvider.GetRequiredService<ILogger<MaximizedVideoWindow>>();
        var maximizedWindow = new MaximizedVideoWindow(video, maximizedWindowLogger);
        
        var mainWindow = Application.Current.MainWindow;
        maximizedWindow.Owner = mainWindow; 

        // Hide main window before showing maximized window
        mainWindow?.Hide();

        maximizedWindow.ShowDialog(); // Show as a dialog to block interaction with main window
                                      // Or use Show() for non-modal

        // Show main window after maximized window is closed
        mainWindow?.Show();

        // After the window is closed, the MediaPlayer is detached in MaximizedVideoWindow_Closing
        // No further action needed here to "restore" in the MainViewModel
        logger.LogInformation($"[MaximizeVideo_Command] Maximize window closed for {video.Device}_{video.Channel}");


        /*
        // OLD LOGIC TO BE REMOVED:
        // 如果当前有其他视频正在最大化播放，则停止它
        if (MaximizedVideo != null && MaximizedVideo != video && MaximizedVideo.IsPlaying)
        {
            MaximizedVideo.StopVideoCommand.Execute(null);
        }

        // 设置新的视频为最大化视频
        // MaximizedVideo 的 setter 会处理UI更新并调用 BindMaximizedVideoViewMediaPlayer
        MaximizedVideo = video;

        // 等待 Dispatcher 完成由 MaximizedVideo setter 触发的操作 (例如 BindMaximizedVideoViewMediaPlayer)
        // BindMaximizedVideoViewMediaPlayer 会设置 video.IsVideoViewLoaded = true
        await Application.Current.Dispatcher.InvokeAsync(() => { /* 空操作以确保队列中的UI任务优先执行 */  

        // 在最大化视图中播放视频
        // VideoItemViewModel 中的 PlayVideoCommand 包含等待 IsVideoViewLoaded 的逻辑
        if (video.PlayVideoCommand.CanExecute(null))
        {
            await video.PlayVideoCommand.ExecuteAsync(null);
        }
       
    }


    // 用于管理最大化视频的属性

    // 用于 UniformGrid 的列数
    public int VideoGridColumns
    {
        get
        {   // Use AvailableItemsControlWidth to determine columns
            if (AvailableItemsControlWidth <= 0 || VideoItems == null || VideoItems.Count == 0)
                return 1; // 默认至少1列

            const double minItemWidth = 480;
            const double itemHorizontalMargin = 8 * 2; // Left and right margin of the Border

            // Calculate thresholds based on minimum item width and margin between items
            // For N columns, total width needed is N * minItemWidth + (N-1) * itemHorizontalMargin
            double widthFor2Columns = (2 * minItemWidth) + (1 * itemHorizontalMargin);
            double widthFor3Columns = (3 * minItemWidth) + (2 * itemHorizontalMargin);

            if (AvailableItemsControlWidth >= widthFor3Columns)
            {
                return 3;
            }
            else if (AvailableItemsControlWidth >= widthFor2Columns)
            {
                return 2;
            }
            return 1; // Default to 1 column if not enough space for 2 or 3
        }
    }

    // Dispose 方法：释放所有 MediaPlayer 和 LibVLC 资源
    public void Dispose()
    {
        // 释放每个视频项的 MediaPlayer 资源
        foreach (var item in VideoItems)
        {
            item.Dispose();
        }
        VideoItems.Clear(); // 清空集合
        VideoItems.CollectionChanged -= OnVideoItemsChanged; // 清理事件订阅

        // 最后释放全局的 LibVLC 实例
        _libvlc?.Dispose();
        _libvlc = null;
        logger.LogInformation("所有Player资源已释放。"); // 使用 Debug.WriteLine
    }
}
